/**
 *
 * icp 通信
 *
 */

const { ipcMain, BrowserWindow, dialog, net, shell } = require('electron')
import * as fs from 'fs'
import icon from '../../../resources/icon.png?asset'
import { checkIp } from '../utils/checkIpConnect'

/**
 * 任务调度
 */
ipcMain.on('schedule', (event, arg) => {
  try {
    console.warn(arg)
    event.sender.send('schedule', true) // 返回一个'pong'
  } catch (error) {
    console.timeEnd('schedule')
    event.sender.send('schedule', false) // 返回一个'pong'
  }
})

/**
 * 检查IP的连通性
 */
ipcMain.on('checkIp', (event, arg) => {
  try {
    let proxyIpList = JSON.parse(arg)
    proxyIpList = [...new Set(proxyIpList)]
    let promissArr = []
    for (let index = 0; index < proxyIpList.length; index++) {
      const element = proxyIpList[index]
      if (element) {
        let ip = element.split(':')
        promissArr.push(checkIp(ip[0], ip[1]))
      }
    }
    console.time('checkIp')
    console.warn('正在检测IP的连通性.......')
    Promise.all(promissArr)
      .then((data) => {
        let tmp = data
        tmp = tmp.filter((item) => item !== false)
        console.timeEnd('checkIp')
        console.warn('检测结果------>>>>', '有效IP:', tmp.length, '检测总量:', proxyIpList.length)
        let str = '检测时间:10s ' + ' 有效IP:' + tmp.length + '  检测总量:' + proxyIpList.length
        event.sender.send('checkIpResult', str) // 返回一个'pong'
      })
      .catch((error) => {
        console.warn(error)
        console.timeEnd('checkIp')
        event.sender.send('checkIpResult', '检测失败！') // 返回一个'pong'
      })
  } catch (error) {
    console.timeEnd('checkIp')
    event.sender.send('checkIpResult', false) // 返回一个'pong'
  }
})

ipcMain.on('hnzjjszc', (event, arg) => {
  console.warn(arg)
  event.returnValue = '主进程收到消息,同步响应'
})

// Returns Promise<any> - Resolves 主进程返回值
ipcMain.handle('some-name', async (event, someArgument) => {
  console.warn(someArgument)
  return someArgument
})

/**
 *
 * 新建窗口打开页面
 *
 */
ipcMain.on('_blank_page', async (event, live_url) => {
  console.warn(live_url)
  // let win = new BrowserWindow({
  //   width: 390,
  //   height: 844,
  //   icon,
  //   autoHideMenuBar: true
  // })
  shell.openExternal(live_url)
  // win.loadURL(live_url, {
  //   userAgent:
  //     'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
  // })
})

/**
 *
 * 选择文件
 *
 */
ipcMain.on('ParseFile', async (event, data) => {
  try {
    console.warn(data)
    let data2 = []
    let result = await dialog.showOpenDialog({
      title: '请选择解析的文件',
      properties: ['multiSelections'],
      //过滤文件后缀
      filters: [
        {
          name: 'txt',
          extensions: ['txt']
        }
      ],
      //打开按钮
      buttonLabel: '选择解析'
    })
    if (!result.canceled) {
      for (const iterator of result.filePaths) {
        let str = fs.readFileSync(iterator)
        str = str.toString('utf-8').split('\r\n')
        let tokenList = str
        for (let index = 0; index < tokenList.length; index++) {
          const element = tokenList[index]
          if (element) {
            data2.push({
              user_id_str: '0',
              updatedAt: new Date(),
              id: index + 1,
              x_tt_token: element,
              token: '',
              status: '封禁'
            })
          }
        }
      }
      event.sender.send('TokenList', data2) // 返回一个'pong'
    }
  } catch (error) {
    console.warn(error)
  }
})

/**
 *
 * 新建窗口打开页面  添加任务页面
 *
 */
ipcMain.on('_add_task_blank_page', async (event, blank_page) => {
  console.warn(blank_page)
  let win = new BrowserWindow({
    title: '直播任务添加',
    width: 600,
    height: 844,
    icon,
    autoHideMenuBar: true,
    webPreferences: {
      // partition: String(+new Date()),
      // preload: join(__dirname, 'preload/index.js'),
      sandbox: false,
      webSecurity: false,
      webviewTag: false,
      contextIsolation: false
    }
  })
  win.loadURL(blank_page, {
    userAgent:
      'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
  })
  // win.webContents.openDevTools()
  win.on('close', () => {
    win.webContents.session.clearStorageData({ storages: ['localStorage'] })
  })
})

/**
 *
 * 获取
 *
 */
ipcMain.on('dyuser', async (event, sec_uid) => {
  console.warn(sec_uid)
  let request = net.request(sec_uid)
  request.setHeader(
    'user-agent',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'
  )
  request.setHeader(
    'cookie',
    'douyin.com; passport_csrf_token=4915f0d69c0487b8ae7742b0db058b3c; passport_csrf_token_default=4915f0d69c0487b8ae7742b0db058b3c; s_v_web_id=verify_leo4sybr_ehvvdjEK_HHVN_4saq_BSUn_rk1mnBstpphc; ttwid=1%7Cx6H0HTjf8tEWMgtafNs0XGC_dwmKIMY0-FsVYHwafw8%7C1677752878%7C20aa81a182fff8c99eb0cedf2f07a2ac7b4a224400bdd5c050c2bd567d9dc453; store-region=cn-hn; store-region-src=uid; odin_tt=52170969baeeebb7d7a42ad72206a0bbf4721b19588662a6e45903e755ce0818e3e8d14572e94bd98a86ef26760fca6bb24b2cee340c6e2c0734017ff8e000ad811522f56db797f1b912c800d7a3980b; __live_version__=%221.1.0.8512%22; live_can_add_dy_2_desktop=%221%22; __ac_nonce=064367d440059857f2e3d; __ac_signature=_02B4Z6wo00f01md9jPAAAIDC5392sbwm4QpnXYhAAP34w959UTjwXIFOSwZbFogB0uHERTM2cn-bEXngdMrcLI6CiCCNGBcYdCk7VEy4rRHW3m9qgI5A5S.3uVuNOyqfcTykLIzz3rd1wo9Vdc; strategyABtestKey=%221681292614.908%22; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtY2xpZW50LWNzciI6Ii0tLS0tQkVHSU4gQ0VSVElGSUNBVEUgUkVRVUVTVC0tLS0tXHJcbk1JSUJEekNCdFFJQkFEQW5NUXN3Q1FZRFZRUUdFd0pEVGpFWU1CWUdBMVVFQXd3UFltUmZkR2xqYTJWMFgyZDFcclxuWVhKa01Ga3dFd1lIS29aSXpqMENBUVlJS29aSXpqMERBUWNEUWdBRXBjZXpGTStxZGlPNVpkbVdFbVA0dzVLSlxyXG5pY2RZUE1iMTNEOXloRnltNTdjYXc5UEExQWs5V2N0RW91WXFrcUFQb0kxOVkyb0l2YTBTOW1JMGo4Y2RCYUFzXHJcbk1Db0dDU3FHU0liM0RRRUpEakVkTUJzd0dRWURWUjBSQkJJd0VJSU9kM2QzTG1SdmRYbHBiaTVqYjIwd0NnWUlcclxuS29aSXpqMEVBd0lEU1FBd1JnSWhBUHdNbEIyUjQ5cVJSSGRLNEVScFRacU5vc0NSUys4QVJIQjVyQlBoSVBYUFxyXG5BaUVBaVFTOXBBd3ArMmFOWUNLaG9XN1A1WFZTeEcwWU5mMm9nbGhaajNNNXYzUT1cclxuLS0tLS1FTkQgQ0VSVElGSUNBVEUgUkVRVUVTVC0tLS0tXHJcbiJ9; home_can_add_dy_2_desktop=%221%22; msToken=h-gzwo0Na9kDqUuJXWFHQvmxetlzJ_Ry8hBLokbkfwL4g73aObAsUccV3XjB3LbYVRCbh5cSt-9tqGbhEpRXwKgoHhj3NREnC0nZ4NHChaWawfvJcgw4iA==; msToken=lLw15zx4y_X_dsQESzQrBTUX0NkSfCerpR2h5hfBzI5AZmmb1BlMwHIukOjUQaf6XPkt3FSWXdavGn6eqSO43967eaMEBh_kQXkZm6dWOdHev2FWDAS83g=='
  )
  request.setHeader(
    'user-agent',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'
  )
  request.on('response', (response) => {
    let chunk_ = ''
    response.on('data', (chunk) => {
      chunk_ += chunk
    })
    response.on('end', () => {
      event.sender.send('dyuser', chunk_.toString('utf-8')) // 返回一个'pong'
    })
  })
  // request.on('response', (response) => {
  //   response.on('data', (chunk) => {
  //     event.sender.send('dyuser', chunk.toString()) // 返回一个'pong'
  //   })
  //   response.on('end', () => {})
  // })
  request.end()
})

/**
 *
 * 选择文件 全参token解析
 *
 */
ipcMain.on('allParameter', async (event, data) => {
  try {
    console.warn(data)
    let data2 = []
    let result = await dialog.showOpenDialog({
      title: '请选择解析的文件',
      properties: ['multiSelections'],
      //过滤文件后缀
      filters: [
        {
          name: 'txt',
          extensions: ['txt']
        }
      ],
      //打开按钮
      buttonLabel: '选择解析'
    })
    if (!result.canceled) {
      for (const iterator of result.filePaths) {
        let str = fs.readFileSync(iterator)
        str = str.toString('utf-8').split('\r\n')
        let tokenList = str
        for (let index = 0; index < tokenList.length; index++) {
          try {
            const element = tokenList[index]
            let obj = JSON.parse(element)
            Object.assign(obj, Object.values(obj.account)[0])
            data2.push(Object.assign({ extra: obj }))
          } catch (error) {
            console.warn(index)
          }
        }
      }
      event.sender.send('allParameter', data2) // 返回一个'pong'
    }
  } catch (error) {
    console.warn(error)
  }
})
